#include "io-context.h"

#include <boost/asio.hpp>

#include "util/logger/logger.h"


static const char *title() {
    return "IOContext ";
}

IOContext::IOContext() {
}

IOContext::~IOContext() {
}

asio::io_context &IOContext::provider() {
    return ioc_;
}

void IOContext::exec() {
    while (!stopped_) {
        try {
            ioc_.run();
        }
        catch (const std::bad_alloc &e) {
            LOGE << title() << "memory alloc failed: " << e.what();
            throw;
        }
        catch (const std::exception &e) {
            LOGE << title() << "unhandled exception: " << e.what();
        }
    }
}

void IOContext::stop() {
    stopped_ = true;
    ioc_.stop();
}

void IOContext::post(std::function<void()> &&action) {
    ioc_.post(std::move(action));
}
